package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioProperties minioProperties ;

    @Autowired
    private MinioClient minioClient;

    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //1. 判断桶是否存在，不存在则创建新的，并设置访问策略
        if(!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build())){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            String config = String.format("""
                    {
                        "Version": "2012-10-17",
                        "Statement": [
                            {
                                "Effect": "Allow",
                                "Principal": {
                                    "AWS": [
                                        "*"
                                    ]
                                },
                                "Action": [
                                    "s3:GetObject"
                                ],
                                "Resource": [
                                    "arn:aws:s3:::%s/*"
                                ]
                            }
                        ]
                    }
                    """, minioProperties.getBucketName());
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(config).build());
        }

        //2. minio的文件存储

        String uuidStr = UUID.randomUUID().toString().replaceAll("-","");
        String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) ;
        String fileName = file.getOriginalFilename();

        fileName = uuidStr+"-"+dateStr + fileName ;

        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                        .object(fileName)
                        .contentType(file.getContentType())
                        .stream(file.getInputStream(), file.getSize(), -1)
                .build());
        // http://192.168.174.100:9000/lease/uuid-20211209111111-xxxx.jpg
        String url = minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+fileName ;
        log.info("=======================================================");
        log.info(url);
        return url;
    }
}
